﻿using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MyMap
{
    public partial class FeatureAttributeTable : Form
    {
        public FeatureAttributeTable()
        {
            InitializeComponent();
        }

        private IFeatureLayer m_featureLayer;

        public FeatureAttributeTable(IFeatureLayer featureLayer)
        {
            InitializeComponent();
            m_featureLayer = featureLayer;
        }

        private void tableLoaded(object sender, EventArgs e)
        {
            IFeatureClass featureClass = m_featureLayer.FeatureClass;
            DataTable table = new DataTable();
            IFields fields = featureClass.Fields;

            // 循环添加字段到DataTable
            for (int i = 0; i < fields.FieldCount; i++)
            {
                IField field = fields.get_Field(i);
                DataColumn column = new DataColumn(field.Name);
                column.DataType = System.Type.GetType("System.String");
                table.Columns.Add(column);
            }

            // 遍历要素并添加属性行
            IFeatureCursor featureCursor = featureClass.Search(null, false);
            IFeature feature = featureCursor.NextFeature();
            while (feature != null)
            {
                DataRow row = table.NewRow();
                for (int i = 0; i < fields.FieldCount; i++)
                {
                    row[i] = feature.get_Value(i)?.ToString() ?? ""; // 增加空值判断，避免异常
                }
                table.Rows.Add(row);
                feature = featureCursor.NextFeature();
            }

            dataGridView1.DataSource = table;
        }
    }
}
